package org.psyduck.admin.dictitems.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.psyduck.admin.dictitems.eneity.DictItems;
import org.psyduck.admin.dictitems.service.DictItemsService;
import org.psyduck.common.constant.Constants;
import org.psyduck.common.model.PageJsonBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("dict/items")
public class DictItemsController {

    @Autowired
    DictItemsService dictItemsService;

    @RequestMapping("list")
    public PageJsonBean list(Page page,DictItems dictItems){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(Constants.BaseEntity.CREATE_DATE);
        queryWrapper.select("id","value","label","dict_id","remarks","sort");
        if(StrUtil.isNotBlank(dictItems.getLabel())){
            queryWrapper.like("label",dictItems.getLabel());
        }
        if(StrUtil.isNotBlank(dictItems.getDictId())){
            queryWrapper.like("dict_id",dictItems.getDictId());
        }
        if(StrUtil.isNotBlank(dictItems.getValue())){
            queryWrapper.like("value",dictItems.getValue());
        }
        return PageJsonBean.success(dictItemsService.page(page,queryWrapper));
    }

    @CacheEvict(value = "admin" ,key = "'getDictItems'")
    @PreAuthorize("hasAuthority('dict:items:save')")
    @RequestMapping("save")
    public String save(DictItems dictItems){
        dictItemsService.saveOrUpdate(dictItems);
        return dictItems.getId();
    }

    @CacheEvict(value = "admin" ,key = "'getDictItems'")
    @PreAuthorize("hasAuthority('dict:items:delete')")
    @RequestMapping("delete")
    public Boolean delete(String id){
        return dictItemsService.removeById(id);
    }

    @RequestMapping("getSort")
    public Integer getSort(String dictId) {
        Integer sort = dictItemsService.getDao().getSort(dictId);
        if(null == sort){
            return 10;
        }
        return sort;
    }

}
